import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useTestStore = defineStore('test', () => {
  const testHistory = ref([])
  const currentTest = ref(null)
  const isTesting = ref(false)
  const urlList = ref([])
  let workers = []
  const MAX_WORKERS = navigator.hardwareConcurrency || 4
  let testInterval = null
  
  const extractLinksFromHtml = (html, baseUrl) => {
    const links = new Set()
    
    // 使用正则表达式匹配所有 href 属性
    const hrefRegex = /href=["'](.*?)["']/g
    let match
    
    while ((match = hrefRegex.exec(html)) !== null) {
      try {
        let href = match[1]
        
        // 忽略特殊链接
        if (!href || 
            href.startsWith('javascript:') || 
            href.startsWith('mailto:') || 
            href.startsWith('tel:') ||
            href === '#' ||
            href === '/') {
          continue
        }
        
        // 移除锚点部分
        href = href.split('#')[0]
        if (!href) continue
        
        // 处理相对路径
        let fullUrl
        try {
          if (href.startsWith('/')) {
            fullUrl = new URL(href, baseUrl.origin).href
          } else if (!href.startsWith('http')) {
            fullUrl = new URL(href, baseUrl).href
          } else {
            fullUrl = href
          }
          
          const linkUrl = new URL(fullUrl)
          
          // 只保留同域名的链接
          if (linkUrl.hostname === baseUrl.hostname) {
            // 规范化 URL
            if (!linkUrl.pathname.endsWith('/') && !linkUrl.pathname.includes('.')) {
              linkUrl.pathname += '/'
            }
            links.add(linkUrl.href)
          }
        } catch (e) {
          console.error('URL 解析错误:', href, e)
        }
      } catch (e) {
        console.error('链接处理错误:', e)
      }
    }
    
    return Array.from(links).sort()
  }
  
  const fetchLinks = async (url) => {
    try {
      const baseUrl = new URL(url)
      
      // 使用 XMLHttpRequest 来获取完整的 HTML 内容
      const html = await new Promise((resolve, reject) => {
        const xhr = new XMLHttpRequest()
        xhr.timeout = 60000 // 60秒超时
        
        xhr.onload = () => {
          if (xhr.status >= 200 && xhr.status < 300) {
            resolve(xhr.responseText)
          } else {
            reject(new Error(`HTTP Error: ${xhr.status}`))
          }
        }
        
        xhr.onerror = () => reject(new Error('Network Error'))
        xhr.ontimeout = () => reject(new Error('Request Timeout'))
        
        xhr.open('GET', url)
        xhr.send()
      })
      
      // 从 HTML 中提取链接
      const links = extractLinksFromHtml(html, baseUrl)
      
      if (links.length === 0) {
        console.log('未找到链接，将只测试主 URL')
        urlList.value = [url]
      } else {
        console.log('找到的链接:', links)
        urlList.value = links
      }
      
      return urlList.value
      
    } catch (error) {
      console.error('抓取链接时出错:', error)
      // 如果出错，使用主 URL
      urlList.value = [url]
      return urlList.value
    }
  }

  const sendRequest = async (url, ip, mode = 'normal') => {
    const startTime = Date.now()
    try {
      if (mode === 'dos') {
        // 优化DOS模式，使用更激进的请求策略
        const controller = new AbortController()
        const timeoutId = setTimeout(() => controller.abort(), 2000) // 2秒超时
        
        try {
          const response = await fetch(`http://${ip}:80`, {
            method: 'GET',
            mode: 'no-cors',
            cache: 'no-cache',
            signal: controller.signal,
            headers: {
              'Cache-Control': 'no-cache',
              'Pragma': 'no-cache'
            }
          });
          clearTimeout(timeoutId)
          
          const endTime = Date.now()
          return {
            url,
            ip,
            success: true,
            responseTime: endTime - startTime
          }
        } catch (error) {
          clearTimeout(timeoutId)
          throw error
        }
      } else {
        // 普通模式也添加超时控制
        const controller = new AbortController()
        const timeoutId = setTimeout(() => controller.abort(), 5000) // 5秒超时
        
        try {
          const response = await fetch(url, {
            method: 'GET',
            signal: controller.signal,
            headers: {
              'Accept': 'application/json, text/plain, */*',
              'Cache-Control': 'no-cache',
              'Pragma': 'no-cache'
            }
          });
          clearTimeout(timeoutId)
          
          const endTime = Date.now()
          let responseData = null;
          
          try {
            responseData = await response.text();
          } catch (e) {
            console.warn('Failed to parse response:', e);
          }
          
          return {
            url,
            ip,
            success: true,
            statusCode: response.status,
            statusText: response.statusText,
            responseData: responseData,
            responseTime: endTime - startTime,
            headers: Object.fromEntries(response.headers)
          }
        } catch (error) {
          clearTimeout(timeoutId)
          throw error
        }
      }
    } catch (error) {
      const endTime = Date.now()
      return {
        url,
        ip,
        success: false,
        responseTime: endTime - startTime,
        error: error.message,
        errorType: error.name
      }
    }
  }

  const startTest = async (config) => {
    try {
      currentTest.value = null
      isTesting.value = true
      
      if (config.mode === 'dos') {
        if (!config.ip) {
          throw new Error('DOS测试模式需要有效的IP地址')
        }
        urlList.value = [`http://${config.ip}`]
      } else {
        urlList.value = [config.url]
      }
      
      if (urlList.value.length === 0) {
        throw new Error('未找到可测试的链接')
      }

      currentTest.value = {
        id: Date.now(),
        ...config,
        startTime: new Date(),
        totalRequests: 0,
        successRequests: 0,
        failedRequests: 0,
        avgResponseTime: 0,
        statusCodes: {},
        apiStats: urlList.value.map(url => ({
          endpoint: url,
          ip: config.ip,
          totalRequests: 0,
          successRequests: 0,
          failedRequests: 0,
          avgResponseTime: 0,
          minResponseTime: Infinity,
          maxResponseTime: 0,
          responseTimes: [],
          statusCodes: {},
          lastResponse: null,
          requestsPerSecond: 0
        }))
      }

      // 创建并启动 workers
      const workerCount = Math.min(MAX_WORKERS, Math.ceil(config.concurrentUsers / 1000));
      const usersPerWorker = Math.ceil(config.concurrentUsers / workerCount);
      
      for (let i = 0; i < workerCount; i++) {
        const worker = new Worker('/src/workers/stress-worker.js');
        
        worker.onmessage = (e) => {
          if (e.data.type === 'stats') {
            const stats = e.data.data;
            const apiStats = currentTest.value.apiStats[0];
            
            // 更新统计数据
            apiStats.totalRequests = stats.totalRequests;
            apiStats.successRequests = stats.successRequests;
            apiStats.failedRequests = stats.failedRequests;
            apiStats.requestsPerSecond = stats.requestsPerSecond;
            
            // 处理每个请求的结果
            stats.results.forEach(result => {
              if (result.statusCode) {
                apiStats.statusCodes[result.statusCode] = (apiStats.statusCodes[result.statusCode] || 0) + 1;
              }
              
              apiStats.responseTimes.push({
                time: Date.now(),
                value: result.responseTime,
                statusCode: result.statusCode
              });
              
              if (apiStats.responseTimes.length > 1000) {
                apiStats.responseTimes = apiStats.responseTimes.slice(-1000);
              }
              
              apiStats.minResponseTime = Math.min(apiStats.minResponseTime, result.responseTime);
              apiStats.maxResponseTime = Math.max(apiStats.maxResponseTime, result.responseTime);
              apiStats.avgResponseTime = Math.floor(
                apiStats.responseTimes.reduce((sum, item) => sum + item.value, 0) / 
                apiStats.responseTimes.length
              );
              
              if (result.success) {
                apiStats.lastResponse = {
                  statusCode: result.statusCode,
                  responseData: result.data
                };
              } else {
                apiStats.lastResponse = {
                  error: result.error
                };
              }
            });
            
            // 更新总体统计
            currentTest.value.totalRequests = apiStats.totalRequests;
            currentTest.value.successRequests = apiStats.successRequests;
            currentTest.value.failedRequests = apiStats.failedRequests;
            currentTest.value.avgResponseTime = apiStats.avgResponseTime;
            currentTest.value.statusCodes = {...apiStats.statusCodes};
          }
        };
        
        workers.push(worker);
        
        // 启动 worker
        worker.postMessage({
          type: 'start',
          config: {
            ...config,
            url: urlList.value[0],
            concurrentUsers: usersPerWorker
          }
        });
      }

      // 设置测试结束定时器
      setTimeout(() => {
        stopTest();
      }, config.duration * 1000 + 1000);

    } catch (error) {
      isTesting.value = false;
      throw error;
    }
  }
  
  const stopTest = () => {
    // 停止所有 workers
    workers.forEach(worker => {
      try {
        worker.postMessage({ type: 'stop' });
        worker.terminate();
      } catch (error) {
        console.error('停止 worker 时出错:', error);
      }
    });
    workers = [];
    
    // 确保状态被重置
    isTesting.value = false;
    
    if (currentTest.value) {
      // 添加结束时间
      currentTest.value.endTime = new Date();
      
      // 计算最终的成功率和统计数据
      const apiStats = currentTest.value.apiStats[0];
      if (apiStats.totalRequests > 0) {
        apiStats.successRate = Math.floor((apiStats.successRequests / apiStats.totalRequests) * 100);
        currentTest.value.successRate = apiStats.successRate;
        
        // 计算总测试时长（秒）
        const duration = Math.floor((currentTest.value.endTime - currentTest.value.startTime) / 1000);
        currentTest.value.actualDuration = duration;
        
        // 计算平均 RPS
        currentTest.value.averageRps = Math.floor(apiStats.totalRequests / duration);
      }
      
      // 添加到历史记录
      testHistory.value.unshift({...currentTest.value});
    }
  }
  
  const updateTestStats = (stats) => {
    if (currentTest.value) {
      Object.assign(currentTest.value, stats)
    }
  }
  
  const getTestById = (id) => {
    return testHistory.value.find(test => test.id === id)
  }
  
  const clearHistory = () => {
    testHistory.value = []
  }
  
  return {
    testHistory,
    currentTest,
    isTesting,
    urlList,
    startTest,
    stopTest,
    updateTestStats,
    getTestById,
    clearHistory,
    fetchLinks
  }
}) 